/* This file is part of remurder
 *
 * Copyright (C) 2014  Hein-Pieter van Braam <hp@tmm.cx>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include <SDL/SDL.h>

#include "display.h"

SDL_Surface *surface = NULL;

void init_sdl() {
	if (SDL_Init(SDL_INIT_VIDEO) < 0) {
		fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError());
		exit(1);
	}

	atexit(SDL_Quit);
}

void create_window(int width, int height) {
	screen = SDL_SetVideoMode(width, height, 16, SDL_SWSURFACE);
	if (screen == NULL) {
		fprintf(stderr, "Couldn't set video mode: %s\n", SDL_GetError());
		exit(1);
	}
}

int check_events() {
	SDL_Event e;
	while (SDL_PollEvent(&e)) {
		switch (e.type) {
		case SDL_KEYDOWN:
			return 1;
			break;
		case SDL_QUIT:
			exit(0);
			break;
		default:
			break;
		}
	}
	return 0;
}

void wait_for_keypress() {
	int done = 0;

	while (!done) {
		SDL_Delay(100);
		done = check_events();
	}
}

void display_buffer(int width, int height, char *cur_buffer, char *prev_buffer, int delay, char* changed_blocks) {
	int x, y;
	char *inp, *outp;


	if (! surface) {
		surface = SDL_CreateRGBSurface(SDL_SWSURFACE, width * 2, height * 2, 8, 0, 0, 0, 0);
	}

	if (SDL_SetPalette(surface, SDL_LOGPAL, colors, 0, NCOLORS) < 0) {
		fprintf(stderr, "Couldn't set palette\n");
	}

	SDL_LockSurface(surface);

	inp = cur_buffer;
	outp = surface->pixels;
	
	for(y = 0; y < height / 8; ++y) {
		for(x = 0; x < width / 8; ++x) {
			if(*changed_blocks) {
				for(int k = 0; k < 8; ++k) {
					for(int l = 0; l < 8; ++l) {
						memset(outp + (k * (width * 4)) + (l * 2), *(inp + (k * width) + l), 2);
						memset(outp + (k * (width * 4)) + (width * 2) + (l * 2), *(inp + (k * width) + l), 2);
					}
				}
			}
			inp += 8;
			outp += 16;
			changed_blocks++;
		}
		inp += width * 7;
		outp += width * 4 * 7;
		//outp += width;
		//outp += (width * 2) * 7;
	}

	SDL_UnlockSurface(surface);

	if (SDL_BlitSurface(surface, NULL, screen, NULL) < 0) {
		fprintf(stderr, "BlitSurface error: %s\n", SDL_GetError());
	}

	SDL_Flip(screen);

	if(delay == 0)
		wait_for_keypress();
	else
		SDL_Delay(delay);

	//SDL_FreeSurface(surface);
	check_events();
}
